import json,sys,os,copy
import IONData
import nrrd
import numpy as np
if hasattr(sys.modules[__name__], '__file__'):
	_file_name = __file__
else:
	_file_name = inspect.getfile(inspect.currentframe())
CURRENT_FILE_PATH = os.path.dirname(_file_name)


class Project:
    def __init__(self):
        annotationRes = iondata.getAnnotation()
        self.annotationMask,header = nrrd.read(annotationRes[1],index_order='F')
        pass
    def CalculateRegion(self,neurontree):
        self.neurontree=neurontree

        # Calculate the region of the neuron tree

        self.projection={}
        self.projectionLeft={}
        self.projectionRight={}
        for edge in self.neurontree.edges:
            for i in range(len(edge.data)-1):
                point = edge.data[i]
                length=np.linalg.norm(np.array(edge.data[i].xyz)-np.array(edge.data[i+1].xyz))
                regionlabel = int(self.annotationMask[int(point.x/10),int(point.y/10),int(point.z/10)])
                if regionlabel not in self.projection:
                    self.projection[regionlabel] = 0
                self.projection[regionlabel]+=length
                if point.z>5700:
                    if regionlabel not in self.projectionRight:
                        self.projectionRight[regionlabel] = 0
                    self.projectionRight[regionlabel]+=length
                else:
                    if regionlabel not in self.projectionLeft:
                        self.projectionLeft[regionlabel] = 0
                    self.projectionLeft[regionlabel]+=length
                    



if __name__=="__main__":
    import SwcLoader
    import BrainRegion
	
    iondata = IONData.IONData()
    neurontree = iondata.getNeuronTreeByID('192106','007.swc')
    project = Project()
    project.CalculateRegion(neurontree)
    project.projection
    
    br = BrainRegion.BrainRegion()
    br.resulation=25
    br.praseJson()
    brproperty=BrainRegion.RegionProperty(copy.deepcopy(br))
    brproperty.setProperty(project.projection)
    brproperty.print()
